<template>
	<div class="newShop">
		<div class="newShop_top">
			<div class="into_index">首页<i class="el-icon-close"></i></div>
			<div class="current">新建商品<i class="el-icon-close"></i></div>
		</div>
		<div class="newShop_title">
			<div class="newShop_title_left">在售商品/<i>{{text}}</i></div>
			<div class="newShop_title_right">
				<button class="newShop_title_right_btn" v-if="id != 1" @click="handerBase">返回</button>
			</div>
		</div>
		<div class="newShop_tabs">
			<div class="newShop_tabs_title">
				<div
				@click="handerTabs(i)"
				class="newShop_tabs_title_information"
				:class="[tabsIndex == i ? 'tabs_active' : '']"
				v-for="(v,i) in tabs" :key="i"
				>{{v}}</div>
			</div>
			<!-- 基本信息 -->
			<div class="newShop_tabs_content_box" v-if="information">
				<div class="newShop_tabs_content_boxs">
					<!-- 基本信息 -->
					<div class="newShop_tabs_content">
						<div class="newShop_tabs_content_left">基本信息</div>
						<div class="newShop_tabs_content_right">
							<form>
								<!-- 商品名称 -->
								<div class="shopName">
									<div class="shopName_name" :class="{'rules' : nameColor}">商品名称</div>
									<div class="shopName_input">
										<input :class="{'rules_input' : nameNull}" type="text" v-model="form.name" @blur="handerName">
										<div class="shopName_input_title">
											<font v-if="nameNull">商品名称不能为空</font>
											<font v-if="unitNull">商品单位不能为空</font>
										</div>
									</div>
									<div class="shopName_unit">
										<input :class="{'rules_input' : unitNull}" type="text" placeholder="单位,如个/件/包" v-model="form.unit" @blur="handerUnit">
									</div>
								</div>
								<!-- 关键字 -->
								<div class="keyword">
									<div class="keyword_left">关键字</div>
									<div class="keyword_right">
										<input type="text" v-model="form.keywords">
										<div class="keyword_right_title">
											商品关键字，能准确搜到商品的，比如：海尔电视|电视 之类的
										</div>
									</div>
								</div>
								<!-- 商品类型 -->
								<div class="shoptype">
									<div class="shoptype_left">商品类型</div>
									<div class="shoptype_right">
										<div class="shoptype_right_radio">
											<el-radio v-model="form.shoptype" label="1">实体商品</el-radio>
											<el-radio v-model="form.shoptype" label="2">虚拟商品</el-radio>
											<el-radio v-model="form.shoptype" label="3">卡密</el-radio>
											<el-radio v-model="form.shoptype" label="4">批发商品</el-radio>
											<el-radio v-model="form.shoptype" label="5">计次/计时商品</el-radio>
										</div>
										<div class="shoptype_right_title">
											商品类型，商品保存后无法修改，请谨慎选择
										</div>
									</div>
								</div>
								<!-- 商品分类 -->
								<div class="classif">
									<div class="classif_left">商品分类</div>
									<div class="classif_right">
										<el-cascader 
										@change="handerClassif"
										:options="cateList"
										:props="cate"
                    v-model="form.classification"
										:show-all-levels="false"
										placeholder="请选择商品分类"></el-cascader>
									</div>
								</div>
								<!-- 商品图片 -->
								<div class="shopimg">
									<div class="shopimg_left">商品图片</div>
									<div class="shopimg_right">
										<input class="shopimg_right_title" readonly :class="[form.img.length == 0 ? 'input_No' : '' ]" v-model="form.img" placeholder="批量上传图片"/>
										<input class="shopimg_right_file" type="file" accept="image/png, image/jpeg, image/gif, image/jpg" disabled title="" @change="handerFile">
										<div class="shopimg_right_btn">选择图片</div>
									</div>
								</div>
								<div class="shopImg" v-if="imagesUrl.length != 0">
                  <div class="shopImgBox" v-for="(item,index) in imagesUrl" :key="index">
									    <img :src="item.image_path" alt="">
                      <div class="shopImgDelete"><i class="el-icon-delete" @click="deleteImg(index)"></i></div>
                  </div>
                  <div style="clear:both;"></div>
                </div>
                
								
								<!-- 商品属性 -->
								<div class="shoptypes">
									<div class="shoptypes_left">商品属性</div>
									<div class="shoptypes_right">
										<el-checkbox-group v-model="form.shoptypes">
										    <el-checkbox label="1">推荐</el-checkbox>
										    <el-checkbox label="2">新品</el-checkbox>
										    <el-checkbox label="3">热卖</el-checkbox>
											<el-checkbox label="4">包邮</el-checkbox>
											<el-checkbox label="5">不参与会员折扣</el-checkbox>
										 </el-checkbox-group>
									</div>
								</div>
							</form>
						</div>
					</div>
					<!-- 商品信息 -->
					<div class="newShop_tabs_shopinfo">
						<div class="newShop_tabs_shopinfo_left">商品信息</div>
						<div class="newShop_tabs_shopinfo_right">
							<form>
								<!-- 商品价格 -->
								<div class="shopprice">
									<div class="shopprice_left">商品价格</div>
									<div class="shopprice_right">
										<div class="shopprice_right_box">
											<div class="shopprice_right_box_title">售价</div><input type="text" v-model="form.price" />
											<div class="shopprice_right_box_title">元 原价</div><input type="text" v-model="form.priced" />
											<div class="shopprice_right_box_title">元 底价</div><input type="text" readonly v-model="floorPrice" />
											<div class="shopprice_right_box_title">元</div>
										</div>
										<!-- <div class="shopprice_right_box">
                                            <div class="shopprice_right_box_title">底价</div><input type="text" v-model="floorPrice" />
											<div class="shopprice_right_box_title">元</div>
                                        </div> -->
										<div class="shopprice_right_title">
											尽量填写完整，有助于商品销售的数据分析
										</div>
										<div class="shopprice_right_payment">
											<el-checkbox-group v-model="form.payment">
												<el-checkbox label="1">支持货到付款</el-checkbox>
												<el-checkbox label="2">支持收银台</el-checkbox>
												<el-checkbox label="3">支持发票</el-checkbox>
											</el-checkbox-group>
										</div>
									</div>
								</div>
								<!-- 运费设置 -->
								<div class="freight">
									<div class="freight_left">运费设置</div>
									<div class="freight_right">
										<div class="freight_right_top">
											<el-radio v-model="form.freight" label="1">运费模板</el-radio>
											<el-select v-model="form.template" placeholder="选择模板">
											    <el-option
												 v-for="v in freightAll"
												 :key="v.move_id"
												 :label="v.freight_name"
												 :value="v.move_id"></el-option>
											  </el-select>
										</div>
										<div class="freight_right_bottom">
											<el-radio v-model="form.freight" label="2">统一邮费</el-radio>
											<div class="freight_right_bottom_price">
												<input type="text" v-model="form.freightPrice">
												<div class="freight_right_bottom_price_text">元</div>
											</div>
										</div>
									</div>
								</div>
								<!-- 上架 -->
								<div class="shelves">
									<div class="shelves_left">上架</div>
									<div class="shelves_right">
										<el-radio v-model="form.shelves" label="0">否</el-radio>
										<el-radio v-model="form.shelves" label="1">上架</el-radio>
									</div>
								</div>
								<!-- 上架时间 -->
								<div class="shelvesTime">
									<div class="shelvesTime_left">是否选择上架时间</div>
									<div class="shelvesTime_right">
										<el-radio v-model="form.shelvesTime" label="0">否</el-radio>
										<el-radio v-model="form.shelvesTime" label="1">是</el-radio>
										<el-date-picker
										      v-model="form.shelves_time"
										      type="daterange"
											    :disabled="form.shelvesTime=='0'?true:false"
										      range-separator="至"
										      start-placeholder="开始日期"
										      end-placeholder="结束日期"
											    value-format="yyyy-MM-dd">
										    </el-date-picker>
										<div class="shelvesTime_right_title">
											商品在选择时间内自动上架，过期自动下架
										</div>
									</div>
								</div>
							</form>
						</div>
					</div>
				</div>
				<div class="newShop_tabs_content_btn">
					<button class="save" @click="save(1)">下一步</button>
				</div>
			</div>
			<!-- 规格/库存 -->
			<div class="newShop_specifications" v-if="specifications">
				<div class="newShop_specifications_box">
					<div class="newShop_specifications_box_left">规格/库存</div>
					<div class="newShop_specifications_box_right">
						<form>
							<div class="coding">
								<div class="coding_left">编码</div>
								<div class="coding_right">
									<div class="codings">编码</div><input class="coding_ipt" :class="{'ipt_actives' : !hiddYesNo}" type="text" v-model="form.codings" />
									<div class="codings">条码</div><input class="coding_ipt" :class="{'ipt_actives' : !hiddYesNo}" type="text" v-model="form.codingss" />
									<div class="codings">重量</div><input class="coding_ipt" :class="{'ipt_actives' : !hiddYesNo}" type="text" v-model="form.codingsss" />
									<div class="codings">克</div>
								</div>
							</div>
							<div class="inventory">
								<div class="inventory_box">
									<div class="inventory_box_left">库存</div>
									<div class="inventory_box_right">
										<input type="text" v-model="form.inventory" :class="{'ipt_actives' : !hiddYesNo}" />
										<div class="inventory_box_right_box"><div :class="{'hidd_active' : hiddIpt}" @click="handerIpt" class="hidd_ipt"><i class="el-icon-check"></i></div>显示库存</div>
										<el-radio v-model="form.reduInventory" label="1">拍下减库存</el-radio>
										<el-radio v-model="form.reduInventory" label="2">付款减库存</el-radio>
										<el-radio v-model="form.reduInventory" label="3">永不减库存</el-radio>
									</div>
								</div>
								<div class="inventory_title">
									<div class="inventory_title_left"></div>
									<div class="inventory_title_right">商品的属于数量，如启用多规格或为虚拟卡密产品，则此处设置无效</div>
								</div>
							</div>
							<div class="yesNo">
								<div class="yesNo_box">
									<div class="yesNo_box_left"></div>
									<div class="yesNo_box_right">
										<div class="yesNo_box_right_box"
										:class="{'yesNo_active' : hiddYesNo}"
										@click="handerYesNo"
										>
											<i class="el-icon-check"></i>
										</div>
										启用商品规格
									</div>
								</div>
								<div class="yesNo_title">
									<div class="yesNo_title_left"></div>
									<div class="yesNo_title_right">
										启用商品规格后，商品的规格及库存以商品规格为准。库存设置为0则会到“已售罄”，手机也不会显示，-1为不限制
									</div>
								</div>
							</div>
               
							<div class="specTitle" v-if="!hiddYesNo">
								1.拖动规格克调整规格显示顺序，更改规格及规格项后请点击下方的【刷新规格项目表】来更新数据。<br />
								2.每一种规格代表不同型号，例如颜色为一种规格，尺寸为一种规格，如果设置多规格，手机用户必须每一种规格都选择一个规格项，才能添加购物车或购买。
							</div> 
              <!--  v-for="(v,i) in form.specifAll" :key="i" -->
							<div class="addSpacItem" v-if="!hiddYesNo">
								<div class="addSpacItem_top">
									<div class="addSpacItem_top_box">
										<input type="text" v-model="title" >
										<div class="addItems" @click="addSpecif"><i class="el-icon-plus"></i>添加规格</div>
									</div>
									<div class="addSpacItem_top_text" v-if="hiddspecifs">
										规格名称不能为空
									</div>
								</div>
								<div class="addSpacItem_bottom">
									<ul>
                     <!-- v-for="(item,index) in v.child" :key="index"
                    	v-dragging="{ list: v.child, item: item, group: 'index' }" -->
										<li v-for="(item,index) in list" :key="index">
                      <div class="sku_title">
                        <h5>{{item.title}}</h5>
                        <div class="li_down" @click="downSpecif(index)"><i class="el-icon-close"></i></div>
                        <div class="spec_file">
                          <i class="el-icon-upload2" v-if="!item.img"></i>
                          <input type="file" v-if="!item.img" disabled @change="handerFiles($event,index)"/>
                          <img :src="item.img" alt="">
                        </div>
                        <input type="text" v-model="item.value" placeholder="请输入规格值" password />
                        
                        <div class="addBtn" @click="addSku_child(index)">添加</div>
                      </div>

                      <!-- 循环规格属性值 -->
                      <div class="sku_child" style="display:flex;" v-for="(item1,index1) in item.list" :key="index1">
                        <div class="li_select">
                          <img :src="item1.img" alt=""/>
                        </div>
                        <span>{{item1.value}}</span>
                        <div class="li_down" @click="downSpecif_child(index,index1)"><i class="el-icon-close"></i></div>
                        <div class="li_rank"><i class="el-icon-rank"></i></div>
                      </div>
                    </li>
									</ul>
								</div> 
							</div>
               
							<div class="refresh" v-if="!hiddYesNo">
								<div class="refresh_btn">
									<!-- <button @click="addSpecifs"><i class="el-icon-plus"></i>添加规格</button> -->
									<button type="button" @click="refreshSku"><i class="el-icon-refresh-left"></i>刷新规格项目表</button>
								</div>
								<div class="refresh_title" v-if="hiddtitle">
									规格发生变化，请刷新规格项目表
								</div>
							</div>
               
							<div v-if="hiddsku">
								<div class="detailed">
                  <!-- 规格表内容 -->
                 <table>
                  <thead>
                      <tr>
                          <th v-for="(item, index) in tableTitle" :key="index"  >{{item}}</th>
                          <th v-if="tableTitle.length">底价</th>
                      </tr>
                  </thead>
                  <tbody>
                      <tr v-for="(item,index) in tableContent" :key="index">
                        <td v-for="(item2,index2) in item" :class="item2.type=='规格'?'type':''" :key="index2">
                            <div v-if="item2.type=='规格'">{{item2.value}}</div>
                            <input v-if="item2.type=='库存'" v-model="item2.value" style="width:100px"/>
                            <input v-if="item2.type=='原价'" v-model="item2.value" style="width:100px"/>
                            <input v-if="item2.type=='售价'" v-model="item2.value" style="width:100px"/>
                            <input v-if="item2.type=='供货价'" value="无权限" readonly style="width:100px"/>
                        </td>
                        <!-- 计算每个规格底价 -->
                          <td>
                            <input style="width:100px" readonly type="text" :value="calcula(item)">
                          </td>
                      </tr>
                  </tbody>
                  </table>
                </div>
							</div>
						</form>
					</div>
				</div>
				<div class="newShop_specifications_btn">
					<button class="bast" @click="save(0)">上一步</button>
					<button class="save" @click="save(2)">下一步</button>
				</div>
			</div>
			<!-- 商品详情 -->
			<div class="newShop_details" v-if="details">
				<div class="newShop_details_box">
					<div class="newShop_details_box_left">内容</div>
					<div class="newShop_details_box_right">
						<form>
							<div class="subtitle">
								<div class="subtitle_left">商品副标题</div>
								<div class="subtitle_right">
									<input type="text" v-model="form.subtitle">
								</div>
							</div>
							<div class="shorttitle">
								<div class="shorttitle_left">商品短标题</div>
								<div class="shorttitle_right">
									<input type="text" v-model="form.shorttitle">
								</div>
							</div>
							<div class="shorttitle">
								<div class="shorttitle_left">商品详情</div>
								<div class="shorttitle_right">
									<!-- <VueEditor :config="config" ref='myeditor'/> -->
								<div><!--上传图片时得加载画面-->
								<VueEditor style="width: 100%" 
									useCustomImageHandler 
                                    disabled
									@image-added="handleImageAdded"
									v-model="form.details"></VueEditor>
    							</div>
                </div>
							</div>
						</form>
					</div>
				</div>
				<div class="newShop_details_btn">
					<button class="bast" @click="save(1)">上一步</button>
					<!-- <button class="save" @click="saveFile">保存信息</button> -->
				</div>
			</div>
		</div>
	</div>
</template>

<script>
// import VueEditor from "vue-word-editor";
// import "quill/dist/quill.snow.css";
import upload from "@/apis/mall";
import { setTimeout } from "timers";
import { VueEditor } from "vue2-editor";
import { log } from "util";
import { isIP } from "net";
export default {
  // props:{
  //   product_id:{
  //     type:'string',
  //     default:''
  //   }
  // },
  data() {
    return {
      title: "", //规格名称
      list: [], //表中生成前的数据
      tableTitle: [], //表头
      tableContent: [], //生成后表中的数据
      id: "",
      text: "新增商品",
      information: true,
      specifications: false,
      details: false,
      tabs: ["编辑基本信息", "规格/库存", "编辑商品详情"],
      tabsIndex: 0,
      detailedTitle: [
        "",
        "库存",
        "现价",
        "原价",
        "供货价",
        "编码",
        "条码",
        "重量（克）"
      ],
      nameColor: false, // 用户没有输入时
      nameNull: false, // 商品名称为空
      unitNull: false, // 商品单位为空
      hiddIpt: false, // 是否显示库存
      hiddspecifs: false, // 规格项为空时
      hiddsku: false, // 规格项为空时规格列表不显示
      hiddtitle: false, // 刷新规格表提示文字
      hiddYesNo: true, // 是否启用商品规格
      imagesUrl: [], //商品图片
      img: [], // 规格图片
      fileList: [],
      dialogImageUrl: "",
      dialogVisible: false,

      // 分类列表
      cateList: [],
      cate: {
        value: "cate_id",
        label: "cate_name",
        children: "child",
        expandTrigger: "hover"
      },
      // 运费模板
      freightAll: [],
      trNum: 1,
      sku_value: [], //属性值组
      form: {
        name: "", // 商品名字
        unit: "件", // 单位
        keywords: "", // 关键字
        shoptype: "1", // 商品类型
        classification: "", // 商品分类
        img: [], // 商品图片(轮播图)
        shoptypes: [], // 商品属性
        price: "", // 售价
        priced: "", // 原价
        cost: "", // 供货价
        payment: [], // 付款方式
        freight: "1", // 运费设置
        template: "", // 运费模板
        freightPrice: "", // 邮费
        shelves: "1", // 上架
        shelvesTime: "0", // 上架时间
        shelves_time: [], // 选择时间
        subtitle: "", // 商品副标题
        shorttitle: "", // 商品短标题
        codings: "", // 编码
        codingss: "", // 条码
        codingsss: "", // 重量
        inventory: "", // 库存
        details: "",
        according: "1", // 是否显示库存
        reduInventory: "1", // 减库存
        specsType: "1", // 单多规格
        specifAll: [], // 规格项列表
        sku: [], // 规格列表

        spec_sku: [
          // {
          //   cost_price: "", // 规格供货价
          //   primary_price: "", // 规格原价
          //   prices: "", // 规格销售价
          //   num: "", // 规格库存
          //   spec_code: "", // 规格编码
          //   spec_barcode: "", // 规格条码
          //   spec_weight: "" // 规格重量
          // }
        ],
        spec_typelist: [] // 规格属性列表
      },
      floorPrice:null,//底价
    };
  },
  mounted() {
    // console.log(product_id,123456);
    this.Id();
    // 拖动排序
    this.$dragging.$on("dragged", value => {});
    this.init();
  },
  methods: {
    // 获取页面id
    Id() {
      console.log(this.$route.query);
      let id = this.$route.query.id;
      if (id!=1) {
        this.$axios
          .post("/api/root/ProductShop/detail", { product_id: id })
          .then(res => {
            console.log(res);
            if (res.code == 1) {
              let data = res.data;
              this.form.id = data.id;
              this.form.name = data.product_title;
              this.form.unit = data.unit;
              this.form.keywords = data.keyword;
              this.form.classification = data.cate_id;
              console.log(data.round_imgs);
              let imgId = data.round_imgs.map(item=>item.img_id)
              imgId.map(item=>{this.form.img.push(item)})
              console.log(imgId);
              // this.form.img.concat(imgId)
               console.log(this.form.img);
              this.imagesUrl = data.round_imgs;
              // this.imagesUrl.push(data.round_imgs.map(item=>item.image_path))
              console.log(this.imagesUrl);
              this.form.shoptype = data.product_type.toString();
              this.form.shoptypes = data.s_type.split(",");
              this.form.price = data.price;
              this.form.priced = data.primary_price;
              this.form.cost = data.cost_price;
              this.form.payment = data.pay_way.split(",");
              this.form.freight = data.move_type.toString();
              this.form.template = data.move_id;
              this.form.freightPrice = data.move_price;
              this.form.codings = data.code;
              this.form.codingss = data.barcode;
              this.form.codingsss = data.weight;
              this.form.inventory = data.num;
              this.form.shelves = data.status.toString();
              this.form.shelvesTime = data.set_sale_time.toString();
              this.form.shelves_time = [
                this.$moment(data.start_sale_time*1000).format(
                  "YYYY-MM-DD HH:mm:ss"
                ),
                this.$moment(data.end_sale_time*1000).format("YYYY-MM-DD HH:mm:ss")
              ];
              // console.log(this.form.shelves_time);
              this.form.subtitle = data.subtitle;
              this.form.shorttitle = data.short_title;
              this.form.according = data.is_show_stock;
              this.form.details = data.details;
              this.form.rate = data.rate*100;   ////////////比率(百分比)
              this.floorPrice = data.rate * data.cost_price + Number(data.cost_price);///////底价
              // console.log(this.$refs.myeditor.editor.root.innerHTML);
              // this.$refs.myeditor.editor.clipboard,dangerouslyPasteHtml(0,data.details)
              if (this.form.according == 1) {
                this.hiddIpt = false;
                this.hiddsku = true;
              } else if (this.form.according == 2) {
                this.hiddIpt = true;
              }
              this.form.reduInventory = data.stock_type.toString();

              this.form.specsType = data.specs_type;
              if (this.form.specsType == 1) {
                this.hiddYesNo = true;
              } else if (this.form.specsType == 2) {
                this.hiddYesNo = false;
              }

              //将获取到的parameter值赋值给list
              if(data.parameter.length){
                data.parameter.map(item => {
                  let arr = [];
                  item.child.map(item => {
                    console.log(item);
                    let obj = {
                      value: item.specif ? item.specif : "",
                      img: item.specimg
                    };
                    arr.push(obj);
                  });
                  let obj_list = {
                    title: item.specifs ? item.specifs : "",
                    list: arr
                  };
                  this.list.push(obj_list);
                });
                console.log(this.list);
                console.log(data.parameter);

                //将获取到的sku_list赋值给tableContent

                console.log(data.sku_lst);
                for (let i = 0; i < data.sku_lst.length; i++) {
                  let skuObj = {};
                  let sku_arr = [];
                  //循环生成里面的obj
                  for (let p = 0; p < data.sku_lst[0].attribute.length + 4; p++) {
                    let skuObj = {
                      value: "",
                      type: ""
                    };
                    if (p == data.sku_lst[0].attribute.length + 3) {
                      skuObj.type = "供货价";
                    } else if (p == data.sku_lst[0].attribute.length + 2) {
                      skuObj.type = "售价";
                    } else if (p == data.sku_lst[0].attribute.length + 1) {
                      skuObj.type = "原价";
                    } else if (p == data.sku_lst[0].attribute.length) {
                      skuObj.type = "库存";
                    } else {
                      skuObj.type = "规格";
                      skuObj.key = "";
                    }
                    sku_arr.push(skuObj);
                  }
                  console.log(sku_arr);

                  console.log(data.sku_lst[i].attribute);
                  for (let k = 0; k < data.sku_lst[i].attribute.length; k++) {
                    for (const key in data.sku_lst[i].attribute[k]) {
                      // console.log(key);
                      sku_arr[k].key = data.sku_lst[i].attribute[k].key;
                      sku_arr[k].value = data.sku_lst[i].attribute[k].value;
                    }
                  }
                  sku_arr[sku_arr.length - 1].value = data.sku_lst[i].cost_price;
                  sku_arr[sku_arr.length - 2].value = data.sku_lst[i].price;
                  sku_arr[sku_arr.length - 3].value = data.sku_lst[i].primary_price;
                  sku_arr[sku_arr.length - 4].value = data.sku_lst[i].num;
                  this.tableContent.push(sku_arr); //然后把每一株数据push到tableContent
                }
                console.log(this.tableContent);

                //获取tabletitle
                for (let n = 0; n < this.tableContent[0].length - 4; n++) {
                  this.tableTitle.push(this.tableContent[0][n].key);
                }
                this.tableTitle.push("库存", "原价", "售价", "供货价");
                console.log(this.tableTitle);
              }
            }
          });
      }
    },

     // 计算每个规格底价
    calcula(item){
      let index = this.tableContent[0].length-1; //供货价下标
      let index1 = this.tableContent[0].length-2; //售价下标
      let costPrice = item[index].value;  //供货价
      let nowPrice = item[index1].value;  //售价
      // 底价
      let all = costPrice * (this.form.rate/100)+Number(costPrice)
      // 判断底价是否大于售价
      if(all>nowPrice){
        all = nowPrice
      }
      return all
    },

    //富文本上传图片
    handleImageAdded(file, Editor, cursorLocation, resetUploader) {
    //   var formData = new FormData();
    //   formData.append("file", file);
    //   console.log(formData);
    //   this.$axios
    //     .post("/api/client/base/uploadfile", formData)
    //     .then(result => {
    //       console.log(result);
    //       // 你上传路径返回的url
    //       let url = result.data.data.url;
    //       console.log(url);
    //       Editor.insertEmbed(cursorLocation, "image", url);
    //       resetUploader();
    //     })
    //     .catch(err => {
    //       console.log(err);
    //     });
    },

    // 调分类数据
    init() {
      this.$axios.get("/api/admin/shop/Cate/cateLst", {}).then(res => {
        console.log(res,123123);
        if (res.code == 1) {
          this.cateList = res.data.data;
        }
      });
      this.$axios
        .post("/api/admin/shop/freight/lst", { store_id: 1 })
        .then(res => {
          if (res.data.code == 1) {
            this.freightAll = res.data;
          }
        });
    },
    // 返回
    handerBase() {
      this.$router.go(-1);
    },
    // 检测商品名字是否有输入
    handerName() {
      if (this.form.name == "") {
        this.nameColor = true;
        this.nameNull = true;
      } else {
        this.nameColor = false;
        this.nameNull = false;
      }
    },
    handerUnit() {
      if (this.form.unit == "") {
        this.nameColor = true;
        this.unitNull = true;
      } else {
        this.nameColor = false;
        this.unitNull = false;
      }
    },
    // 切换导航栏
    handerTabs(i) {
      this.tabsIndex = i;
      if (i == 0) {
        this.information = true;
        this.specifications = false;
        this.details = false;
      } else if (i == 1) {
        this.information = false;
        this.specifications = true;
        this.details = false;
      } else if (i == 2) {
        this.information = false;
        this.specifications = false;
        this.details = true;
      }
    },
    // 获取用户选中的商品分类
    handerClassif(e) {
      console.log(e);
      this.form.classification = e[e.length - 1];
    },

    // 上传商品图片
    handerFile(evnet) {
      let file = evnet.target.files[0];
      // this.form.img.push(this.getObjectUrl(files));
      // console.log(this.form.img);
      console.log(event);
      let reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = v => {
        console.log(v);
        // console.log(reader.result);
        let imgPath = {
          // img_id:'',
          image_path: ""
        };
        imgPath.image_path = v.target.result;
        this.imagesUrl.push(imgPath);
        console.log(this.imagesUrl);
      };
      let form = new FormData();
      console.log(form);
      form.append("file", file);
      this.$axios
        .post("/api/client/base/uploadfile", form)
        .then(res => {
          console.log(res);
          if (res.data.code == 1) {
            this.$message({
              showClose: true,
              message: "上传成功",
              type: "success"
            });
          }
          let src = res.data.data.id;
          console.log(src);
          this.form.img.push(src);
        })
        .catch(err => {
          this.$message({
            showClose: true,
            message: "上传失败",
            type: "error"
          });
        });
    },


  // 删除商品图片
  deleteImg(index){
    console.log(index);
    console.log(this.form.img);
    this.imagesUrl.splice(index,1)
    this.form.img.splice(index,1)
    console.log(this.imagesUrl)
    console.log(this.form.img);
  },

    // 上传规格图片
    handerFiles(event, index, index1) {
      let file = event.target.files[0];
      let form = new FormData();
      form.append("file", file);
      console.log(event);
      console.log(index);
      this.$axios.post("/api/client/base/uploadfile", form).then(res => {
        if (res.data.code == 1) {
          this.$message({
            showClose: true,
            message: "上传成功",
            type: "success"
          });
        }
        let src = res.data.data.id;
        // this.form.specifAll[i].child[index].specimg = src;
        let data = res.data.data;
        console.log(data);
        this.list[index].img = data.url;
        this.list[index].img_id = data.id;
        console.log(this.list);
      });
    },
    // 是否显示库存
    handerIpt() {
      this.hiddIpt = !this.hiddIpt;
      if (this.hiddIpt) {
        this.form.according = 1;
      } else {
        this.form.according = 2;
      }
    },
    handerYesNo() {
      this.hiddYesNo = !this.hiddYesNo;
      this.form.codings = "";
      this.form.codingss = "";
      this.form.codingsss = "";
      this.form.inventory = "";
      if (!this.hiddYesNo) {
        this.form.specsType = 2;
      } else {
        this.form.specsType = 1;
      }
    },

    // 打开添加规格
    // addSpecifs() {
    //   this.hiddYesNo = false;
    //   this.hiddtitle = true;
    // //新增规格
    // //
    // },

    //添加规格项
    addSpecif() {
      if (!this.title) {
        // return this.$message.warning("请填写规格再添加");
        this.hiddspecifs = true;
        return;
      }
      let allTitle = this.list.map(item => {
        return item.title;
      });
      if (allTitle.indexOf(this.title) != -1) {
        return this.$message.warning("已添加过该规格");
      }
      console.log(allTitle);
      this.title;
      this.hiddspecifs = false;
      this.list.push({
        img: "",
        title: this.title, //规格
        list: [], //规格值
        sort: this.list.length,
        new: this.tableContent.length ? true : false //用于判断是否新规格
      });
      this.title = "";
      console.log(this.list);
    },

    //添加规格属性值
    addSku_child(index) {
      if (!this.list[index].value) {
        return this.$message.warning("请填写规格值再添加");
      } else {
        let allSku = this.list[index].list.map(item => {
          return item.value;
        });
        if (allSku.indexOf(this.list[index].value) != -1) {
          return this.$message.warning("已添加过该规格值");
        }
        this.list[index].list.push({
          img: this.list[index].img,
          img_id: this.list[index].img_id,
          value: this.list[index].value, //规格值
          new: this.tableContent.length ? true : false //用于判断是否新规格值
        });
        console.log(this.list);
        this.list[index].value = "";
        this.list[index].img = "";
      }
    },

    // 删除规格
    downSpecif(index) {
      const title = this.list[index].title;
      const tempList = JSON.parse(JSON.stringify(this.list)); //删之前先保存一份用于后面判断
      this.list.splice(index, 1);
      //删除完让sort重新获取值  不然后面添加规格排序会乱
      this.list.forEach((item, index) => {
        item.sort = index;
      });
      if (!this.tableContent.length) {
        return false;
      }
      // 如果当前删除的规格里面没有值就不用在this.tableContent中删除数据
      if (!tempList[index].list.length) return false;
      // 如果删除的是最后一个规格，则清空所有数据
      if (this.tableContent[0][1].type != "规格") {
        this.tableContent = [];
        this.tableTitle = [];
        return false;
      }
      // 删除表中整列的数据
      this.deleteRowData(title);
      // 递归去重
      for (let i = 0; i < this.tableContent.length; i++) {
        for (let j = i + 1; j < this.tableContent.length; j++) {
          this.recursionJudgeValue(i, j, 0, true);
          if (this.delectFlag) {
            this.tableContent.splice(j, 1);
            j--;
          }
        }
      }
      // 重新生成表头
      this.handleTableHead();
    },
    // 递归去重
    recursionJudgeValue(i, j, count, flag) {
      let tempFlag =
        this.tableContent[i][count].value == this.tableContent[j][count].value;
      let tempCount = count;
      const flag2 = flag && tempFlag;
      if (tempCount < this.list.length) {
        tempCount++;
        this.recursionJudgeValue(i, j, tempCount, flag2);
      } else {
        this.delectFlag = flag2;
      }
    },
    // 删除表中一列的数据
    deleteRowData(title) {
      for (let i = 0; i < this.tableContent.length; i++) {
        value: for (let j = 0; j < this.tableContent[i].length; j++) {
          if (this.tableContent[i][j].key == title) {
            this.tableContent[i].splice(j, 1);
            break value;
          }
        }
      }
    },

    // // 删除当前规格
    downSpecif_child(index, index1) {
      this.hiddtitle = true;
      if (!this.tableContent.length) {
        this.list[index].list.splice(index1, 1);
        return false;
      }
      const length = this.list[index].list.length;
      const value = this.list[index].list[index1].value;
      const title = this.list[index].title;
      this.list[index].list.splice(index1, 1);
      if (length > 1) {
        // 如果有多个值时就删除this.tableContent中所有带有这个值的那一行
        content: for (let i = 0; i < this.tableContent.length; i++) {
          value: for (let j = 0; j < this.tableContent[i].length; j++) {
            if (this.tableContent[i][j].value == value) {
              this.tableContent.splice(i, 1);
              i--;
              break value;
            }
          }
        }
      } else {
        // 如果只有一个值 那么就把值从所有数据中删除 就是删除列
        this.list[index].new = true; //删除掉这个值 那么这个规格没有值了  就等同于是新添加的
        this.deleteRowData(title);
        if (
          this.tableContent.length === 1 &&
          this.tableContent[0][0].type != "规格"
        ) {
          // 如果删除的是最后的规格和最后一个值就清空所有数据
          this.tableContent = [];
          this.tableTitle = [];
          return false;
        }
        // 重新生成表头
        this.handleTableHead();
      }
    },

    // 刷新规格列表
    refreshSku() {
      this.hiddtitle = false;
      this.hiddsku = true;

      //讲添加的规格项进行排序
      function specsortFunction(propertyName) {
        return function(object1, object2) {
          let value1 = object1[propertyName].length;
          let value2 = object2[propertyName].length;
          if (value1 < value2) {
            return -1;
          } else if (value1 > value2) {
            return 1;
          } else {
            return 0;
          }
        };
      }
      // this.list.sort(specsortFunction("list"));
      console.log(this.this);
      console.log(this.form.spec_typelist);
      console.log(this.list);
      if (!this.list.length) return false;
      let flag = false;
      flag = this.list.some(item => {
        return item.list.length;
      });
      if (!flag) return false;
      this.handleTableHead();
      this.handleTableData();
    },

    // 生成表头
    handleTableHead() {
      this.tableTitle = [];
      this.list.forEach(item => {
        if (item.list.length) {
          this.tableTitle.push(item.title);
        }
      });
      this.tableTitle.push("库存", "原价", "售价", "供货价");
    },

    // 处理表格中的数据
    handleTableData(num) {
      const listData = this.list.filter(item => item.list.length); //去掉没有值的规格
      if (this.tableContent.length) {
        // 表格中数据不是第一次添加时
        let tempList = []; //用于存放新加的规格和值
        let tempContentList = this.tableContent.length; //记录上一次数据的总长度
        listData.forEach((item, index) => {
          item.list.forEach((item2, index2) => {
            if (item2.new) {
              //新添加的值
              let flag = false; // flag用于判断新值有没有添加进tempList
              let count = -1;
              flag = tempList.some((sitem, sindex) => {
                count++;
                return sitem.title == item.title;
              });
              if (flag) {
                //如果添加过则直接在里面的list追加
                tempList[count].list.push(item2);
              } else {
                //没添加过就添加一个新的对象
                tempList.push({
                  title: item.title,
                  list: [item2],
                  new: item.new,
                  sort: item.sort
                });
              }
            }
          });
        });
        tempList.forEach(item => {
          const list = [];
          // list代表所有新值的规格和其他规格匹配的数据
          if (item.new && item.list.length == 1) {
            // 如果新加的规格的值只有一个，那么直接在每一列加新值
            for (let i = 0; i < tempContentList; i++) {
              this.tableContent[i].splice(item.sort, 0, {
                type: "规格",
                value: item.list[0].value,
                sort: item.sort,
                key: item.title
              });
            }
          } else {
            // 如果新加的规格的值大于一个，那么先在每一列插入新值
            // 然后再拿其他值互相匹配
            if (item.new && item.list.length > 1) {
              for (let i = 0; i < tempContentList; i++) {
                this.tableContent[i].splice(item.sort, 0, {
                  type: "规格",
                  value: item.list[0].value,
                  sort: item.sort,
                  key: item.title
                });
              }
              // 第一个值已经加进去，所以要删掉
              item.list.splice(0, 1);
            }
            // 先把新加的值加进去
            list.push(item);
            listData.forEach(listItem => {
              listItem.list.forEach(listItem2 => {
                item.list.forEach(item2 => {
                  if (listItem2.value == item2.value) {
                    // 上面的新值已经加进去所以要在原来的listData中做标记
                    // 避免下面出现重复的组合
                    listItem2.disabled = true;
                  }
                });
              });
            });
            listData.forEach(listItem => {
              if (listItem.title !== item.title) {
                // 深拷贝避免影响原来的数据
                let tempListItem = JSON.parse(JSON.stringify(listItem));
                for (let count = 0; count < tempListItem.list.length; count++) {
                  if (tempListItem.list[count].disabled) {
                    //已经加过的值删掉
                    tempListItem.list.splice(count, 1);
                    count--;
                  }
                }
                list.push(tempListItem); // 加进list组合成新的数据
              }
            });
            list.sort((n1, n2) => n1.sort - n2.sort); //排序 避免新加的表中数据和表头对应不上
            this.transformData(list);
          }
        });
        // 生成后把所有的值初始化 用于下次生成判断新值
        this.list.forEach(item => {
          item.new = false;
          item.list.forEach(item2 => {
            item2.new = false;
            item2.disabled = false;
          });
        });
        return false;
      }
      this.transformData(listData);
    },
    transformData(list) {
      const arr = [];
      // 这里改造一下数据
      list.forEach(item => {
        const tempList = [];
        item.list.forEach(item2 => {
          let obj = {
            type: "规格",
            value: item2.value,
            sort: item.sort,
            key: item.title
          };
          tempList.push(obj);
        });
        arr.push(tempList);

        console.log(arr);
      });
      // 再改造成真正的表中数据类型
      const data = this.cartesianProductOf(...arr);
      // 这里给表中每行加一些写死的值
      data.forEach(item => {
        item.push({
          type: "库存",
          value: "",
          rowspan: 1
        });
        item.push({
          type: "原价",
          value: "",
          rowspan: 1
        });
        item.push({
          type: "售价",
          value: "",
          rowspan: 1
        });
        item.push({
          type: "供货价",
          value: "",
          rowspan: 1
        });
      });
      //与原来的数据合并
      this.tableContent.push(...data);
      console.log(this.tableContent, "tableContent");
    },
    // 笛卡尔积
    cartesianProductOf() {
      return Array.prototype.reduce.call(
        arguments,
        function(a, b) {
          var ret = [];
          a.forEach(function(a) {
            b.forEach(function(b) {
              ret.push(a.concat(b));
              // ret.push([...a, ...b]);
            });
          });
          return ret;
        },
        [[]]
      );
    },

    // 下一步/上一步
    save(i) {
      // console.log(this.form.sku);
      // console.log(this.form.specifAll);
      // console.log(this.form.spec_sku);
      this.handerTabs(i);
    },

    // 保存
    saveFile() {
      let url = this.form.id
        ? "/api/admin/shop/product/edit"
        : "/api/admin/shop/product/add";
      let store_id = 1;
      let product_id = this.form.id;
      let product_title = this.form.name;
      let unit = this.form.unit;
      let keyword = this.form.keywords;
      let cate_id = this.form.classification;
      let product_type = this.form.shoptype;
      let s_type = [];
      this.form.shoptypes.forEach(v => {
        s_type.push(v);
      });

      s_type = s_type.join(",");
      let price = this.form.price;
      let cost_price = this.form.cost;
      let primary_price = this.form.priced;
      let pay_way = [];
      this.form.payment.forEach(v => {
        pay_way.push(v);
      });
      pay_way = pay_way.join(",");
      let move_type = this.form.freight;
      let move_id = this.form.template;
      let move_price = this.form.freightPrice;
      let status = this.form.shelves;
      let set_sale_time = this.form.shelvesTime;
      let start_sale_time = this.form.shelves_time
        ? new Date(this.form.shelves_time[0]).getTime()
        : "";
      let end_sale_time = this.form.shelves_time
        ? new Date(this.form.shelves_time[1]).getTime()
        : "";
      let code = this.form.codings ? this.form.codings : "";
      // if(this.form.codings == '') {
      // 	code = this.form.spec_sku[0].spec_code;
      // }else {
      // 	code = this.form.codings;
      // }
      let barcode = this.form.codingss ? this.form.codingss : "";
      // if(this.form.codingss == '') {
      // 	barcode = this.form.spec_sku[0].spec_barcode;
      // }else {
      // 	barcode = this.form.codingss;
      // }
      let weight = this.form.codingsss ? this.form.codingsss : "";
      // if(this.form.codingsss == '') {
      // 	weight = this.form.spec_sku[0].spec_weight;
      // }else {
      // 	weight = this.form.codingsss;
      // }
      let is_show_stock = this.form.according;
      let stock_type = this.form.reduInventory;
      let specs_type = this.form.specsType;
      let round_imgs = [];
      this.form.img.forEach(v => {
        round_imgs.push(v);
        console.log(v);
      });
      console.log(this.form.img);
      console.log(this.imagesUrl);
      round_imgs = round_imgs.join(",");
      console.log(round_imgs);
      let subtitle = this.form.subtitle;
      let short_title = this.form.shorttitle;
      // let details = this.$refs.myeditor.editor.root.innerHTML; // 商品详情
      let details = this.form.details; // 商品详情
      let num = this.form.inventory; // 库存
      let parameter = [];
      let sku_c = [];
      let obj = {};
      let child = [];

      this.list.forEach(item => {
        obj = {
          specifs: item.title,
          child: child
        };
        parameter.push(obj);
      });
      for (let i = 0; i < this.list.length; i++) {
        for (let key in this.list[i]) {
          if (key == "list") {
            console.log(this.list[i][key]);
            sku_c.push(this.list[i][key]);
          }
        }
      }
      let k = [];
      for (let x = 0; x < sku_c.length; x++) {}

      //改变每一组的key名字，然后赋值给parameter
      for (let i = 0; i < parameter.length; i++) {
        let arr = [];
        let arr1 = [];
        arr.push(arr1);
        console.log(arr);
        arr[i] = sku_c[i].map(item => ({
          specif: item.value,
          specimg: item.img_id ? item.img_id : ""
        }));
        parameter[i].child = arr[i];
      }
      console.log(sku_c); //============
      console.log(parameter);

      //将对应的每一项信息push到sku_lst中
      let sku_lst = [];
      let sku_obj1 = {};
      this.tableContent.map((item1, index1) => {
        sku_obj1 = {
          sku_id: 0,
          num: item1[item1.length - 4].value,
          primary_price: item1[item1.length - 3].value,
          price: item1[item1.length - 2].value,
          cost_price: item1[item1.length - 1].value,
          attribute: []
        };

        //将每一行的规格push到对应的attribute中
        for (let k = 0; k < item1.length - 4; k++) {
          console.log(item1[k]);
          let obj4 = {
            key: item1[k].key,
            value: item1[k].value
          };
          console.log(obj4);
          // let obj5 = {};
          // obj5[item1[k].key] = item1[k].value;
          sku_obj1.attribute.push(obj4);
        }
        sku_lst.push(sku_obj1);
      });
      //===========================================================
      console.log(sku_obj1);
      console.log(sku_lst);

      console.log(this.form.spec_sku);
      // console.log(sku_lst);
      parameter = JSON.stringify(parameter);
      sku_lst = JSON.stringify(sku_lst);
      console.log(sku_lst);
      console.log(parameter);
      // console.log(sku_lst);
      console.log(this.form.img);
      this.$http
        .post(url, {
          product_id,
          store_id: store_id,
          product_title: product_title,
          unit: unit,
          keyword: keyword,
          cate_id: cate_id,
          product_type: product_type,
          s_type: s_type,
          price: price,
          cost_price: cost_price,
          primary_price: primary_price,
          pay_way: pay_way,
          move_type: move_type,
          move_id: move_id,
          move_price: move_price,
          status: status,
          set_sale_time: set_sale_time,
          start_sale_time: start_sale_time,
          end_sale_time: end_sale_time,
          code: code,
          barcode: barcode,
          weight: weight,
          is_show_stock: is_show_stock,
          stock_type: stock_type,
          specs_type: specs_type,
          round_imgs: round_imgs,
          subtitle: subtitle,
          short_title: short_title,
          details: details,
          num: num,
          parameter: parameter,
          sku_lst: sku_lst
        })
        .then(res => {
          if (res.code == 1) {
            if (this.form.id) {
              this.$message({
                showClose: true,
                message: "修改成功",
                type: "success"
              });
            } else {
              this.$message({
                showClose: true,
                message: "添加成功",
                type: "success"
              });
            }
            this.$router.push({ path: "/shopList" });
            console.log(res);
          }
        })
        .catch(err => {
          console.log(err);
        });
    }
  },
  components: {
    VueEditor
  }
};
</script>

<style lang="less" scoped="scoped">
@import "designerDetail.less";
/deep/ #editor {
  height: 300px;
}
</style>
